package pl.edu.agh.agents.gui.actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import pl.edu.agh.agents.gui.GUI;
import pl.edu.agh.agents.gui.GraphFileFilter;
import pl.edu.agh.agents.gui.GraphUtils;

// dumps current configuration to file
public class LoadAction extends AbstractAction {
	private static final long serialVersionUID = -1940878883959876753L;
	private GUI gui;
	private GraphUtils graphUtils = GraphUtils.getInstance();
	private IterationThread thread;

	public LoadAction(String name, GUI gui, IterationThread thread) {
		super(name);

		this.gui = gui;
		this.thread = thread;
	}

	protected String getGraphPath() {
		String name;
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(gui.getDir());
		chooser.setDialogTitle("Load");

		FileFilter filter = new GraphFileFilter();
		chooser.setFileFilter(filter);
		int returnVal = chooser.showOpenDialog(gui.getGraphComponent());
		if (returnVal != JFileChooser.APPROVE_OPTION) {
			return null;
		}

		name = chooser.getSelectedFile().getAbsolutePath();

		gui.setDir(chooser.getCurrentDirectory());

		System.out.println("You chose to load from this file: " + name);

		return name;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// stop current iterations
		thread.requestStop();

		// ask user or use previous name in reset
		String name = getGraphPath();

		if (name == null) {
			return;
		}

		gui.setGraphPath(name);

		gui.loadGraph(name, true);

		thread.requestStop();

		gui.stopIterationThread();

		graphUtils.colorStates(gui);

	}
}